package com.kitty.game.welfare.service;


import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.base.service.BagService;
import com.kitty.game.config.ChoujiangGift;
import com.kitty.game.config.DaySign;
import com.kitty.game.config.Equip;
import com.kitty.game.config.NewcomerGift;
import com.kitty.game.confirm.model.DoReplenishSignConfirm;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespFestivalLottery;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.item.ItemDataPool;
import com.kitty.game.item.message.RespGiftEquipList;
import com.kitty.game.item.service.ChangeCardService;
import com.kitty.game.map.service.MapService;
import com.kitty.game.mount.message.RespSummonMountNotify;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.pet.bean.PetObject;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.message.ReqGeneralNotify;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.team.message.RespConfirm;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.*;
import com.kitty.game.welfare.message.vo.DailySignGift;
import com.kitty.game.welfare.message.vo.GiftItem;
import com.kitty.game.welfare.message.vo.GiftsInfo;
import com.kitty.game.welfare.message.vo.LotteryInfo;
import com.kitty.game.welfare.model.CommonFetchedData;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.concurrent.ThreadLocalRandom;


import com.kitty.game.utils.AsktaoUtil;
import com.kitty.game.utils.StringUtil;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.welfare.message.ReqDoReplenishSign;
import com.kitty.game.welfare.message.ReqNewLotteryDraw;
import com.kitty.game.welfare.message.ReqNewLotteryInfo;
import com.kitty.game.welfare.message.ReqShenmiDaliPick;
import com.kitty.game.welfare.message.RespDailySign;
import com.kitty.game.welfare.message.RespNewBieGift;
import com.kitty.game.welfare.message.RespNewLotteryDraw;
import com.kitty.game.welfare.message.RespNewLotteryDrawDone;
import com.kitty.game.welfare.message.RespNewLotteryInfo;
import com.kitty.game.welfare.message.RespOpenWelfare;
import com.kitty.game.welfare.message.RespShenmiDaliPick;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
public class WelfareService {

    @Autowired
    RoleService roleService;
    @Autowired
    EquipService equipService;
    @Autowired
    BagService bagService;
    @Autowired
    PetService petService;
    @Autowired
    BroadcastService broadcastService;
    @Autowired
    ServerService serverService;
    @Autowired
    MallService mallService;
    @Autowired
    Dao dao;
    @Autowired
    MapService mapService;

    private CommonFetchedData randomData;
    private CommonFetchedData randomDataLeiji;

    private int[] ints = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120};
    /**
     * 砸蛋领奖的在线时长秒数
     */
    private List<Integer> eggRewardTimes;

    /**
     * 特等奖 一等奖用这个
     */
    private static final String GIFT_MESSAGE_BIG = "特大喜讯！惊闻#Y{0}#n在本期充值好礼活动中通过#R{1}#n幸运地抽中#R{2}#n获得了#R{3}#n！真是羡煞旁人！人品好到没人性啊！";
    /**
     * 二等
     */
    private static final String GIFT_MESSAGE = "真是天降鸿福，传闻#Y{0}#n人品大爆发在本期充值好礼活动中通过#R{1}#n幸运地抽中#R{2}#n获得了#R{3}#n！真是令人羡慕啊！";

    @PostConstruct
    private void init() {
        eggRewardTimes = new ArrayList<>(8);
        /**列表中数字是分钟数*/
        List<Integer> list = Arrays.asList(5, 10, 15, 20, 25, 30, 40, 50, 60);
        int secSum = 0;
        for (int min : list) {
            secSum += min * 60;
            eggRewardTimes.add(secSum);
        }
        randomData = dao.fetch(CommonFetchedData.class, CommonConst.role_random_activity);
        if (randomData == null) {
            randomData = new CommonFetchedData();
            randomData.setData(Json.toJson(new NutMap()));
            randomData.setType(CommonConst.role_random_activity);
            dao.insertOrUpdate(randomData);
        }

        randomDataLeiji = dao.fetch(CommonFetchedData.class, CommonConst.role_random_leiji_activity);
        if (randomDataLeiji == null) {
            randomDataLeiji = new CommonFetchedData();
            randomDataLeiji.setData(Json.toJson(new NutMap()));
            randomDataLeiji.setType(CommonConst.role_random_leiji_activity);
            dao.insertOrUpdate(randomDataLeiji);
        }
    }

    public void resetRandomActivity(Role gm,String content){
        NutMap nutMap = NutMap.NEW();
        nutMap.setv("content",content);
        randomData.setData(Json.toJson(nutMap));
        dao.insertOrUpdate(randomData);
        log.error("重置随机充值活动=={}=={}=={}",gm.getRoleId(),gm.getName(),content);
    }

    public void resetRandomLeijiActivity(Role gm,String content){
        NutMap nutMap = NutMap.NEW();
        nutMap.setv("content",content);
        randomDataLeiji.setData(Json.toJson(nutMap));
        dao.insertOrUpdate(randomDataLeiji);
        log.error("重置随机充值活动=={}=={}=={}",gm.getRoleId(),gm.getName(),content);
    }

    public CommonFetchedData getRandomData() {
        return randomData;
    }

    public void setRandomData(CommonFetchedData randomData) {
        this.randomData = randomData;
    }

    public CommonFetchedData getRandomDataLeiji() {
        return randomDataLeiji;
    }

    public void setRandomDataLeiji(CommonFetchedData randomDataLeiji) {
        this.randomDataLeiji = randomDataLeiji;
    }

    /**
     * 领取新手礼包
     */
    public void getNewcomerGift(ReqGeneralNotify reqGeneralNotify, Role role) {
        int index = Integer.parseInt(reqGeneralNotify.getStatus());
        if (index >= ints.length) {
            return;
        }
        int level = ints[index];
        if (role.getLevel() < level) {
            return;
        }

        List<NewcomerGift> list = DataCache.NEWCOMER_GIFT.get(level);
        short size = bagService.getVacancySize(role);
        if (size < list.size()) {
            MessagePusher.pushMessage(role, new RespMsg("你的包裹不足，还是整理后再来吧。"));
            return;
        }
        String newcomerLevels = role.getExtendBox().getNewcomer();
        if (!StringUtil.isEmpty(newcomerLevels)) {
            if (newcomerLevels.contains(level + "")) {
                return;
            }
        }
        if (newcomerLevels != null) {
            newcomerLevels = newcomerLevels + "_" + level;
        } else {
            newcomerLevels = String.valueOf(level);
        }
        role.getExtendBox().setNewcomer(newcomerLevels);
        role.save();

        RespGiftEquipList equipList = new RespGiftEquipList();
        equipList.setEquipIds(new ArrayList<>());
        for (NewcomerGift newcomerGift : list) {
            if (newcomerGift.getType() == 1) {
                // 装备
                int pos = bagService.getPos(role, false);
                RoleEquip roleEquip = equipService.getNewcomerEquip(role, (short) pos, newcomerGift.getPos(), newcomerGift.getGetLevel());
                equipList.getEquipIds().add(roleEquip.getId());
            } else if (newcomerGift.getType() == 2) {
                // 道具
                equipService.addMall(newcomerGift.getName(), true, role, newcomerGift.getNum());
            } else if (newcomerGift.getType() == 3) {
                // 3代金券
                int roleVoucher = role.getVoucher();
                role.setVoucher(roleVoucher + newcomerGift.getNum());

                RespIconCartoon respIconCartoon = new RespIconCartoon();
                respIconCartoon.setType((short) 3);
                respIconCartoon.setName("代金券");
                respIconCartoon.setParam(String.valueOf(newcomerGift.getNum()));
                MessagePusher.pushMessage(role, respIconCartoon);
            } else if (newcomerGift.getType() == 4) {
                // 首饰
                equipService.getJewelry(role, newcomerGift.getName(), false, newcomerGift.getNum(),true);
            }
        }
        MessagePusher.pushMessage(role, equipList);
        if (level == 10) {
            SpringUtils.getBean(NewTaskService.class).pushGuide(role, (short) 61);
        }
        newcomerList(role);
    }


    public void newcomerList(Role role) {
        RespNewBieGift respNewBieGift = new RespNewBieGift();
        String temp = role.getExtendBox().getNewcomer();
        respNewBieGift.setGifts(new ArrayList<>());
        for (Map.Entry<Integer, List<NewcomerGift>> entry : DataCache.NEWCOMER_GIFT.entrySet()) {
            int level = entry.getKey();
            List<NewcomerGift> list = entry.getValue();
            GiftsInfo giftsInfo = new GiftsInfo();
            respNewBieGift.getGifts().add(giftsInfo);
            if (temp != null && temp.contains("" + level)) {
                giftsInfo.setReceive(true);
            } else {
                giftsInfo.setReceive(false);
            }
            giftsInfo.setLevel((short) level);
            giftsInfo.setGiftItems(new ArrayList<>());

            for (NewcomerGift newcomerGift : list) {
                GiftItem giftItem = new GiftItem();
                giftsInfo.getGiftItems().add(giftItem);

                if (newcomerGift.getType() == 1) {
                    List<String> arrayList = EquipDataPool.getNamesBy(newcomerGift.getGetLevel(), newcomerGift.getPos());
                    String name = newcomerGift.getName();
                    if (!arrayList.isEmpty()) {
                        if (newcomerGift.getPos() == 1) {
                            for (String strings : arrayList) {
                                Equip equip = EquipDataPool.getByName(strings);
                                if (equip.getMenpai() == role.getPolar()) {
                                    name = strings;
                                    break;
                                }
                            }
                        } else if (newcomerGift.getPos() == 2 || newcomerGift.getPos() == 3) {
                            for (String strings : arrayList) {
                                Equip equip = EquipDataPool.getByName(strings);
                                if (equip.getGender() == role.getGender()) {
                                    name = strings;
                                    break;
                                }
                            }
                        } else if (newcomerGift.getPos() == 10) {
                            for (String strings : arrayList) {
                                name = strings;
                            }
                        }
                    }
                    giftItem.setItemName(name);

                } else {
                    giftItem.setItemName(newcomerGift.getName());
                }
                giftItem.setItemLevel(newcomerGift.getLevel());
                giftItem.setNum(newcomerGift.getNum());
            }
        }
        MessagePusher.pushMessage(role, respNewBieGift);
    }

    /**
     * 打开福利
     */
    public void openWelfare(IoSession session, ReqGeneralNotify reqGeneralNotify) {
//        RespOpenWelfare respOpenWelfare = new RespOpenWelfare();
        Role role = SessionUtils.getRoleBySession(session);
        RespOpenWelfare respOpenWelfare = getRespOpenWelfare(role);
        MessagePusher.pushMessage(session, respOpenWelfare);

        RespFestivalLottery respFestivalLottery = new RespFestivalLottery();
        MessagePusher.pushMessage(session, respFestivalLottery);
    }

    public RespOpenWelfare getRespOpenWelfare(Role role) {
        RespOpenWelfare respOpenWelfare = new RespOpenWelfare();
        respOpenWelfare.setLeftTime(getEggNextRemainTime(role));
        respOpenWelfare.setTimes(getEggCanOpenCount(role));
        respOpenWelfare.setLeftTimes(getEggRemainOpenCount(role));
        respOpenWelfare.setFirstChargeState(role.getFirstPayStatus());
        respOpenWelfare.setChargePointFlag((byte)1);
//        respOpenWelfare.setConsumePointFlag((byte)1);

        return respOpenWelfare;
    }

    /**
     * 每日签到
     *
     * @param role
     */
    public void dailySign(Role role) {
        String str = role.getExtendBox().getSignbuSign();
        String today = TimeUtil.formatDate(new Date());
        String dd = TimeUtil.getDay(new Date());
        int size = role.getExtendBox().getSignSize();
        String todaySign = role.getExtendBox().getSignDay();// false今天还未签到，true今天已经签到

        RespDailySign respDailySign = new RespDailySign();
        respDailySign.setMonthDays((byte) TimeUtil.getDaysOfMonth());//当月有多少天
        if (!today.equals(str) && size < Integer.parseInt(dd)) {
            respDailySign.setCanReplenishSign(true);//今天是否可以补签
        } else {
            respDailySign.setCanReplenishSign(false);//今天是否可以补签
        }
        respDailySign.setCanReplenishSign(false);//今天是否可以补签
        if (today.equals(todaySign)) {
            respDailySign.setCanSgin(false);//今天是否可以签到
        } else {
            respDailySign.setCanSgin(true);//今天是否可以签到
        }
        respDailySign.setSignDays((byte) size);//本月签到几次了
        respDailySign.setList(new ArrayList<>());

        for (Map.Entry<Integer, DaySign> entry : DataCache.ID_DAYSIGN.entrySet()) {
            DaySign daySign = entry.getValue();
            DailySignGift dailySignGift = new DailySignGift();
            dailySignGift.setName(daySign.getName());
            dailySignGift.setNum(daySign.getNum());
            respDailySign.getList().add(dailySignGift);
        }

        MessagePusher.pushMessage(role, respDailySign);
    }


    public DailySignGift getSignGift(int size) {
        int id = size + 1;
        DaySign daySign = DataCache.ID_DAYSIGN.get(id);
        if (daySign != null) {
            DailySignGift dailySignGift = new DailySignGift();
            dailySignGift.setName(daySign.getName());
            dailySignGift.setNum(daySign.getNum());
            return dailySignGift;
        }

        return null;
    }

    public void getSignGift(Role role, DailySignGift dailySignGift) {
        if (dailySignGift.getName().equals("银元宝")) {
            roleService.addSiver(role, dailySignGift.getNum(), Reason.SIGN_GIFT);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你领取了签到奖励，获得了#R" + dailySignGift.getNum() + "#n银元宝。"));
        }else if (dailySignGift.getName().equals("金元宝")){
            roleService.addYinde(role,dailySignGift.getNum(),true);
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("你领取了签到奖励，获得了#R" + dailySignGift.getNum() + "#n金元宝。"));
        }else if (dailySignGift.getName().equals("小酒碗")){
            roleService.addYinde(role,dailySignGift.getNum(),true);
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("获得#R"+dailySignGift.getNum()+"阴德！！"));
        }else {
            equipService.addMall(dailySignGift.getName(), true, role, dailySignGift.getNum());
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你领取了签到奖励，获得了#R" + dailySignGift.getName() + "#n。"));
        }
    }

    /**
     * 补签
     *
     * @param session
     * @param reqDoReplenishSign
     */
    public void doReplenishSign(IoSession session, ReqDoReplenishSign reqDoReplenishSign) {
        Role role = SessionUtils.getRoleBySession(session);
        RespConfirm respConfirm = new RespConfirm();
        respConfirm.setTips("是否花费" + AsktaoUtil.getMoneyFormat(2580000) + "文钱进行补签？（每日只可补签一次）");
        MessagePusher.pushMessage(session, respConfirm);
        role.setConfirm(new DoReplenishSignConfirm());
    }


    /**
     * 签到
     */
    public void sign(Role role) {
        String today = TimeUtil.formatDate(new Date());
        if (today.equals(role.getExtendBox().getSignDay())) {
            MessagePusher.pushMessage(role, new RespMsg("今日已经签到。"));
            return;
        }
        DailySignGift dailySignGift = getSignGift(role.getExtendBox().getSignSize());
        if (dailySignGift == null) {
            return;
        }
        role.getExtendBox().setSignDay(today);
        role.getExtendBox().setSignSize(role.getExtendBox().getSignSize() + 1);
        getSignGift(role, dailySignGift);
        role.save();
        dailySign(role);
    }


    public void lotteryDraw(IoSession session, ReqNewLotteryDraw newLotteryDraw) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) return;
        if (role.getTotalCharge() < 0){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值，不能抽奖！！"));
            return;
        }
        if (serverService.getServer().getId() == 10000){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服专线，不能抽奖！！"));
            return;
        }
        byte type = newLotteryDraw.getType();
        session.setAttribute(Const.choujiangType, type);
        choujiangResult(type, role, session);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(new ArrayList<>());
        FiedValue fiedValue = new FiedValue();
        fiedValue.setType((short) 868);
        fiedValue.setVT((byte) 3);
        fiedValue.setValue(role.getExtendBox().getWelfare().getOrDefault("lotteryDraw", 0));
        respUpdate.getList().add(fiedValue);
        MessagePusher.pushMessage(session, respUpdate);

        RespNewLotteryDrawDone respNewLotteryDrawDone = new RespNewLotteryDrawDone();
        MessagePusher.pushMessage(session, respNewLotteryDrawDone);

    }

    public void choujiangResult(byte type, Role role, IoSession session) {
        // 抽奖结果
        ArrayList<ChoujiangGift> allList = new ArrayList<>();
        ArrayList<ChoujiangGift> normalList = new ArrayList<>();
        int total = 0;
        int normalTotal = 0;
        for (ChoujiangGift choujiangGift : DataCache.LOTTERYS) {
            if (choujiangGift.getType() != 4) {
                allList.add(choujiangGift);
                total += choujiangGift.getDae();
            }
            if (choujiangGift.getType() != 0) {
                normalList.add(choujiangGift);
                normalTotal += choujiangGift.getNormal();
            }
        }
        Map<String, Integer> welfare = role.getExtendBox().getWelfare();
        int lotteryDraw = welfare.getOrDefault("lotteryDraw", 0);
        if (type == 1) {
            if (lotteryDraw < 1) {
                return;
            }
        } else if (type == 2) {
            if (lotteryDraw < 10) {
                return;
            }
        } else if (type == 3) {
            if (lotteryDraw < 10) {
                return;
            }
        } else if (type == 4) {
            if (lotteryDraw < 100) {
                return;
            }
        }


        if (type == 1) {
            //普通抽奖一次
            ChoujiangGift choujiangGift = getOne(1, normalTotal, normalList);
            RespNewLotteryDraw respNewLotteryDraw = new RespNewLotteryDraw();
            respNewLotteryDraw.setStr(choujiangGift.getStr());
            respNewLotteryDraw.setLevel(choujiangGift.getType());
            MessagePusher.pushMessage(session, respNewLotteryDraw);
            welfare.put("lotteryDraw", welfare.get("lotteryDraw") - 1);
            role.save();
            log.info("subtractLotteryDraw|小额1|{}|{}|{}",
                    role.getUid(), lotteryDraw, 1);
            send(choujiangGift, role, "普通抽取");
        } else if (type == 3) {
            // 普通抽10次
            ArrayList<ChoujiangGift> arrayList = getTen(role, 1, 10, normalTotal, normalList);
            for (ChoujiangGift choujiangGift : arrayList) {
                RespNewLotteryDraw respNewLotteryDraw = new RespNewLotteryDraw();
                respNewLotteryDraw.setStr(choujiangGift.getStr());
                respNewLotteryDraw.setLevel(choujiangGift.getType());
                MessagePusher.pushMessage(session, respNewLotteryDraw);
                send(choujiangGift, role, "普通抽取");
            }
            /**扣实际抽到的次数*/
            welfare.put("lotteryDraw", welfare.get("lotteryDraw") - arrayList.size());
            log.info("subtractLotteryDraw|小额10|{}|{}|{}",
                    role.getUid(), lotteryDraw, arrayList.size());
            role.save();
        } else if (type == 2) {
            // 大额抽一次
            ChoujiangGift choujiangGift = getOne(0, total, allList);
            RespNewLotteryDraw respNewLotteryDraw = new RespNewLotteryDraw();
            respNewLotteryDraw.setStr(choujiangGift.getStr());
            respNewLotteryDraw.setLevel(choujiangGift.getType());
            MessagePusher.pushMessage(session, respNewLotteryDraw);
            welfare.put("lotteryDraw", welfare.get("lotteryDraw") - 10);
            log.info("subtractLotteryDraw|大额1|{}|{}|{}",
                    role.getUid(), lotteryDraw, 10);
            role.save();
            send(choujiangGift, role, "大额抽取");
        } else if (type == 4) {
            // 大额抽10次 消耗100次
            ArrayList<ChoujiangGift> arrayList = getTen(role,0, 10, total, allList);
            int index = 0;
            for (ChoujiangGift choujiangGift : arrayList) {
                RespNewLotteryDraw respNewLotteryDraw = new RespNewLotteryDraw();
                respNewLotteryDraw.setStr(choujiangGift.getStr());
                respNewLotteryDraw.setLevel(choujiangGift.getType());
                MessagePusher.pushMessage(session, respNewLotteryDraw);
                send(choujiangGift, role, "大额抽取");
                index++;
                if (index >= 10) {
                    break;
                }
            }
            /**扣实际抽到的次数*10 */
            welfare.put("lotteryDraw", welfare.get("lotteryDraw") - (index*10));
            log.info("subtractLotteryDraw|大额10|{}|{}|{}",
                    role.getUid(), lotteryDraw, 10 * index);
            role.save();
        }
    }

    /**
     * 充值抽奖获得
     */
    private void send(ChoujiangGift choujiangGift, Role role, String type) {
        String message = null;
        if (choujiangGift.getType() == 0) {
            message = MessageFormat.format(GIFT_MESSAGE_BIG, role.getName(), type, "特等好礼", choujiangGift.getName());
        } else if (choujiangGift.getType() == 1) {
            message = MessageFormat.format(GIFT_MESSAGE, role.getName(), type, "一等好礼", choujiangGift.getName());
        } else if (choujiangGift.getType() == 2) {
//            message = MessageFormat.format(GIFT_MESSAGE, role.getName(), type, "二等好礼", choujiangGift.getName());
        }

        if (choujiangGift.getStr().contains("首饰")) {
            int level = Integer.parseInt(choujiangGift.getName().substring(0, 2));
            RoleEquip roleEquip = equipService.getRandomJewelry(level, role);
            short newPos = bagService.getPos(role, false);
            if (newPos <= 0) {
                MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，无法获得#R" + roleEquip.getName() + "#n。"));
                return;
            }
            RespNotifyMiscEx respNotifyMiscEx = new RespNotifyMiscEx();
            respNotifyMiscEx.setMsg("你获得了#R1#n" + equipService.getItemUnit(roleEquip.getName()) + "#R" + roleEquip.getName() + "#n。");
            respNotifyMiscEx.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
            MessagePusher.pushMessage(role, respNotifyMiscEx);
        } else if (choujiangGift.getStr().contains("宠物|")) {
            PetObject petObject = PetDataPool.getPetObject(choujiangGift.getName());
            if (SpringUtils.getPetService().isEquippedFull(role)) {
                MessagePusher.pushMessage(role, new RespMsg("对不起，你的宠物栏已满，无法获得#R" + petObject.getName() + "#n。"));
                return;
            }
            Pet pet = petService.addPet(petObject, role, false);
            petService.loadPet(role, pet);
            RespSummonMountNotify respSummonMountNotify = new RespSummonMountNotify();

            respSummonMountNotify.setId(pet.getId());
            MessagePusher.pushMessage(role, respSummonMountNotify);
            RespNotifyMiscEx respNotifyMiscEx = new RespNotifyMiscEx();
            respNotifyMiscEx.setMsg("你获得了一只#R" + petObject.getName() + "#n。");
            respNotifyMiscEx.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
            MessagePusher.pushMessage(role, respNotifyMiscEx);

            RespIconCartoon respIconCartoon = new RespIconCartoon();
            respIconCartoon.setType((short) 2);
            respIconCartoon.setName(petObject.getName());
            respIconCartoon.setParam(petObject.getIcon() + "");
            MessagePusher.pushMessage(role, respIconCartoon);
        } else if (choujiangGift.getStr().contains("物品")) {
            short newPos = bagService.getPos(role, false);
            if (newPos <= 0) {
                MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，无法获得#R" + choujiangGift.getName() + "#n。"));
                return;
            }
            equipService.addMall(choujiangGift, true, role);
            RespNotifyMiscEx respNotifyMiscEx = new RespNotifyMiscEx();
            respNotifyMiscEx.setMsg("你获得了#R1#n" + equipService.getItemUnit(choujiangGift.getName()) + "#R" + choujiangGift.getName() + "#n。");
            respNotifyMiscEx.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
            MessagePusher.pushMessage(role, respNotifyMiscEx);
        } else if (choujiangGift.getStr().contains("装备")) {
            // 随机装备
            short roleLevel = role.getLevel();
            String temp = roleLevel + "";
            if (temp.length() == 3) {
                roleLevel = Short.parseShort(temp.substring(0, 2) + 0);
            } else {
                roleLevel = Short.parseShort(temp.substring(0, 1) + 0);
            }
            short newPos = bagService.getPos(role, false);
            if (newPos <= 0) {
                MessagePusher.pushMessage(role, new RespMsg("你的包裹已满。"));
                return;
            }
            equipService.getEquip(roleLevel, role, newPos, true);
        } else if (choujiangGift.getName().equals("随机变身卡")) {
            List<String> list = new ArrayList<>(ItemDataPool.name2ChangeCard.keySet());
            int index = ThreadLocalRandom.current().nextInt(list.size());
            SpringUtils.getBean(ChangeCardService.class).getChangeCard(role, list.get(index));
        }

        /**最后广播谣言*/
        if (!Strings.isEmpty(message)) {
            broadcastService.sendRumor(message, null);

            /**特等好礼或一等好礼发公告消息*/
            if (choujiangGift.getType() == 0) {
                SpringUtils.getChatService().sendAdnotice(message);
            }else if (choujiangGift.getType() == 1 || choujiangGift.getType() == 2){
                SpringUtils.getChatService().sendNumor(message,null);
            }
        }
    }


    /**
     * 抽十次将
     *
     * @param total
     * @param allList
     * @return
     */
    private ArrayList<ChoujiangGift> getTen(Role role, int type, int times, int total, ArrayList<ChoujiangGift> allList) {
        ArrayList<ChoujiangGift> result = new ArrayList<>();
        int petCount = 0;
        /**循环次数多于抽的次数，因为有可能宠物栏不够时抽到宠物，需要再次抽*/
        for(int i=0, max=times*5; i<max; i++) {
            if(result.size() >= times) {
                break;
            }

            ChoujiangGift choujiangGift = getOne(type, total, allList);
            if (choujiangGift != null) {
                if (choujiangGift.getStr().contains("宠物|")) {
                    if (SpringUtils.getPetService().checkPetPosEnouth(role, (petCount+1))){
                        result.add(choujiangGift);
                        petCount += 1;
                    }
                } else {
                    result.add(choujiangGift);
                }
            }
        }
        return result;
    }


    /**
     * 抽一次将
     *
     * @param total
     * @param allList
     * @return
     */
    private ChoujiangGift getOne(int type, int total, ArrayList<ChoujiangGift> allList) {
        Random random = new Random();
        int result = random.nextInt(total) + 1;
        int temp = 0;
        for (ChoujiangGift choujiangGift : allList) {
            if (type == 1) {
                temp += choujiangGift.getNormal();
            } else {
                temp += choujiangGift.getDae();
            }
            if (result <= temp) {
                log.info("getOne=={}=={}={}={}", temp, result, total, choujiangGift.getName());
                return choujiangGift;
            }
        }
        return null;
    }

    /**
     * 返回奖品列表
     *
     * @param session
     * @param reqNewLotteryInfo
     */
    public void openChoujiangList(IoSession session, ReqNewLotteryInfo reqNewLotteryInfo) {
        RespNewLotteryInfo respNewLotteryInfo = new RespNewLotteryInfo();
        int startTime = new Long(System.currentTimeMillis() / 1000).intValue();
        int endTime = new Long(System.currentTimeMillis() / 1000 + 7 * 24 * 60 * 60).intValue();
        respNewLotteryInfo.setStartTime(startTime);
        respNewLotteryInfo.setEndTime(endTime);
        respNewLotteryInfo.setList(new ArrayList<>());
        for (ChoujiangGift choujiangGift : DataCache.LOTTERYS) {
            LotteryInfo lotteryInfo = new LotteryInfo();
            lotteryInfo.setNo(choujiangGift.getPer());
            lotteryInfo.setName(choujiangGift.getName());
            lotteryInfo.setDesc(choujiangGift.getStr());
            lotteryInfo.setLevel(choujiangGift.getType());
            respNewLotteryInfo.getList().add(lotteryInfo);
        }
        MessagePusher.pushMessage(session, respNewLotteryInfo);
    }

    /**
     * 砸蛋
     *
     * @param session
     * @param reqShenmiDaliPick
     */
    public void zadan(IoSession session, ReqShenmiDaliPick reqShenmiDaliPick) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        Map<Byte, String> zadan = role.getActivity().getZadan();
        if (reqShenmiDaliPick.getPos() == 0) {//砸开全部的蛋
            /**判断是否全部蛋已经砸完*/
            if (isAllOpened(role)) {
                MessagePusher.pushMessage(role, new RespMsg("今日的银蛋已经敲完了，请明日再来吧！"));
                return;
            }

            List<Byte> canOpenPos = getCanOpenPos(role);
            if (canOpenPos == null || canOpenPos.size() == 0) {
                MessagePusher.pushMessage(role, new RespMsg("当前没有可敲开的银蛋，过段时间再来吧！"));
                return;
            }

            for (byte pos : canOpenPos) {
                openEgg(session, role, pos);
            }
        } else if (reqShenmiDaliPick.getPos() <= 8 && reqShenmiDaliPick.getPos() > 0) {//砸开某一个蛋
            if (Strings.isEmpty(zadan.get(reqShenmiDaliPick.getPos()))) {
                openEgg(session, role, reqShenmiDaliPick.getPos());
            }
        } else {
            return;
        }
        role.save();
    }

    /**
     * 是否所有蛋已经砸完
     */
    private boolean isAllOpened(Role role) {
        for (byte pos = 1; pos <= 8; pos++) {
            if (isEggOpend(role, pos) == false) {
                return false;
            }
        }

        return true;
    }

    /**
     * 获得当前可以砸蛋的位置列表
     */
    private List<Byte> getCanOpenPos(Role role) {
        List<Byte> list = new ArrayList<>();
        for (byte pos = 1; pos <= 8; pos++) {
            if (canOpenEgg(role, pos)) {
                list.add(pos);
            }
        }
        return list;
    }

    /**
     * 判断对应位置能否砸蛋
     */
    private boolean canOpenEgg(Role role, byte pos) {
        if (pos < 1 || pos > 8) {
            return false;
        }

        /**判断是否已经领取过*/
        if (isEggOpend(role, pos)) {
            return false;
        }

        /**判断在线时长是否足够*/
//        int onlineSec = SpringUtils.getRoleService().getOnlineSec(role);
//        int needSec = eggRewardTimes.get(pos - 1);
//        if (onlineSec < needSec) {
//            return false;
//        }

        return true;
    }

    private boolean isEggOpend(Role role, byte pos) {
        /**判断是否已经领取过*/
        if (role.getActivity() == null){
            return false;
        }
        Map<Byte, String> zadan = role.getActivity().getZadan();
        if (zadan != null && zadan.containsKey(pos)) {
            return true;
        }

        return false;
    }

    /**
     * 砸蛋一次
     */
    private void openEgg(IoSession session, Role role, byte pos) {
        /**不能砸蛋时返回*/
        if (canOpenEgg(role, pos) == false) {
            String msg = "该银蛋未到开启时间，过段时间再来吧！";
            MessagePusher.pushMessage(role, new RespMsg(msg));
            return;
        }

        String[] gifts = {"经验", "潜能", "道行"};
        byte[] mults = {1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5, 5, 1, 1, 1, 10, 10, 3, 3};
        Random random = new Random();
        String gift = gifts[random.nextInt(gifts.length)];
        byte mult = mults[random.nextInt(mults.length)];
        int value;
        switch (gift) {
            case "道行":
                value = mult * role.getLevel();
                roleService.addTao(role, value);
                break;
            case "经验":
                value = mult * role.getLevel() * 6666;
                roleService.addExp(role, value, 1, role.getPetBox().getFightPetId());
                break;
            case "潜能":
                value = mult * role.getLevel() * 11111;
                roleService.addPot(role, value);
                break;
        }
        Map<Byte, String> zadan = role.getActivity().getZadan();
        zadan.put(pos, gift + ":" + mult);
        RespShenmiDaliPick respShenmiDaliPick = new RespShenmiDaliPick(pos, gift, mult);
        MessagePusher.pushMessage(session, respShenmiDaliPick);
    }

    /**
     * 获得神秘大礼下一次剩余时间
     */
    public int getEggNextRemainTime(Role role) {
        int onlineSec = SpringUtils.getRoleService().getOnlineSec(role);
        for (byte pos = 1; pos <= 8; pos++) {
            int needSec = eggRewardTimes.get(pos - 1);
            if (onlineSec < needSec) {
                return needSec - onlineSec;
            }
        }

        return 0;
    }

    /**
     * 获得神秘大礼当前可抽奖次数
     */
    public byte getEggCanOpenCount(Role role) {
        byte count = 0;
        int onlineSec = SpringUtils.getRoleService().getOnlineSec(role);
        for (byte pos = 1; pos <= 8; pos++) {
            if (isEggOpend(role, pos)) {
                continue;
            }

            int needSec = eggRewardTimes.get(pos - 1);
            if (onlineSec < needSec) {
                continue;
            }

            count += 1;
        }

        return count;
    }

    /**
     * 获得神秘大礼当天剩余可抽奖次数
     */
    public byte getEggRemainOpenCount(Role role) {
        byte count = 0;
        for (byte pos = 1; pos <= 8; pos++) {
            if (isEggOpend(role, pos)) {
                continue;
            }

            count += 1;
        }

        return count;
    }
}
